﻿using DevExpress.LookAndFeel;
using DevExpress.XtraEditors;
using DevExpress.XtraTab;
using EkStudio.com.common.dbconn;
using EkStudio.com.common.session;
using EkStudio.com.ui.form;
using EkStudio.com.ui.form.ExcelReport;
using EkStudio.com.ui.login;
using EkStudio.Com.UI.Interface;
using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Windows.Forms;

namespace EkStudio
{
    public partial class FormMain : DevExpress.XtraEditors.XtraForm
    {

        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(FormMain));

        private DefaultLoginForm login = null;

        private ProjectRootPanel ActivateProject = null;

        private ModuleAttachForm attachForm = null;

        private MenuMapingForm menuForm = null;

        public FormMain()
        {
            InitializeComponent();
            InitForm();
        }


        

        private void InitForm()
        {
            

        }
        /// <summary>
        /// 更新工具栏状态
        /// </summary>
        public void RefreshToolbar()
        {
            if (ActivateProject != null)
            {
                if (!ActivateProject.SaveStatus)
                {
                    TbSave.Enabled = true;
                }
                else
                {
                    TbSave.Enabled = false;
                }
                if (!ActivateProject.SaveAllStatus)
                {
                    TbSaveAll.Enabled = true;
                }
                else
                {
                    TbSaveAll.Enabled = false;
                }
            }
            else
            {
                TbSave.Enabled = false;
                TbSaveAll.Enabled = false;
            }
        }

        public void ChangedCmdStatus(string status)
        {
            TbStatusValue.Caption = status;
        }

        public void WaitCmdStatus()
        {
            TbStatusValue.Caption = "就绪";
        }

        

        //-----------------------------------------事件注册------------------------------------------

        /// <summary>
        /// 保存所有
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void TbSaveAll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ChangedCmdStatus("正在保存数据...");
            if (ActivateProject != null) ActivateProject.saveAll();
            WaitCmdStatus();
            RefreshToolbar();
        }
        /// <summary>
        /// 编译数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TbCompileData_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ActivateProject != null)
            {
                if (!ActivateProject.SaveAllStatus)
                {
                    ActivateProject.AddConsoleText("请先保存后再执行编译", true);
                }
                else
                {
                    if (XtraMessageBox.Show("您确认执行数据库编译吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        ActivateProject.compileDateBase();
                    }
                }

            }
        }


        /// <summary>
        /// 保存当前模块
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TbSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ActivateProject != null)
            {
                ChangedCmdStatus("正在保存数据...");
                ActivateProject.save();
                WaitCmdStatus();
                RefreshToolbar();
            }
            

        }

        /// <summary>
        /// 编译帐套
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TbCompileXml_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ActivateProject != null)
            {
                if (!ActivateProject.SaveAllStatus)
                {
                    ActivateProject.AddConsoleText("请先保存后再执行编译", true);
                }
                else
                {
                    if(XtraMessageBox.Show("您确认执行帐套编译吗?","提示",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        ActivateProject.compileConfig();
                    }
                }
                
            }

        }

        private void TbExitSystem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            saveSkin();
            if (MainTab.TabPages.Count > 0)
            {
                XtraMessageBox.Show("请先关闭帐套后再进行此操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                Application.Exit();
            }
        }

        private void MainTab_CloseButtonClick(object sender, EventArgs e)
        {
            XtraTabPage tab = MainTab.SelectedTabPage ;
            ProjectRootInterface Project = (ProjectRootInterface)tab.Controls[0];
            bool canClose = true;
            if (!Project.SaveAllStatus)//
            {
                DialogResult dr = XtraMessageBox.Show("当前有记录未保存，是否保存？", "提示", MessageBoxButtons.YesNoCancel);
                if(dr == DialogResult.Yes)
                {
                    Project.saveAll();
                }
                else if(dr == DialogResult.Cancel)
                {
                    canClose = false;
                }
            }
            if (canClose)
            {
                Project.Http.LogOut();
                MainTab.TabPages.Remove(tab);
                tab.Dispose();
                if (MainTab.TabPages.Count == 0)
                {
                    TbCompany.EditValue = "";
                    RefreshToolbar();
                }
            }
            
        }

        private void BtStatus_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            saveSkin();
            if (MainTab.TabPages.Count > 0)
            {
                e.Cancel = true;
                XtraMessageBox.Show("请先关闭帐套后再进行此操作","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            }
            
        }

        private void TbLogin_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ChangedCmdStatus("正在登录系统...");

            if(login==null) login = new DefaultLoginForm();
            
            DialogResult dr = login.ShowDialog(this);

            if(dr == DialogResult.OK)
            {
                User user = new User();
                user.Safety = login.LoginType == "安全模式";
                user.Url = login.LoginURL;
                user.UserName = login.LoginUser;
                user.Machine = Dns.GetHostName();
                user.Ipv4add = "";
                IPAddress[] iplist = Dns.GetHostAddresses(user.Machine);
                for (int i = 0; i < iplist.Length; i++)
                {
                    string temp = iplist[i].ToString();
                    if (temp.IndexOf('.') > 0) 
                    {
                        user.Ipv4add = temp;
                        break;
                    }
                }
                HttpConnectUnit http = new HttpConnectUnit(user);
                int result = http.Login(user.UserName, login.LoginPwd);
                if (result == 0)//登录成功
                {
                    XtraTabPage page = new XtraTabPage();
                    page.ImageIndex = 20;
                    page.Text = login.LoginURL;
                    ProjectRootPanel Project = new ProjectRootPanel(this,http);
                    Project.UserInfo = user;
                    Project.Dock = DockStyle.Fill;
                    Project.Http = http;
                    page.Controls.Add(Project);
                    MainTab.TabPages.Add(page);
                    MainTab.SelectedTabPage = page;

                    ActivateProject = Project;
                    RefreshToolbar();
                }
                else if(result == 1)
                {
                    XtraMessageBox.Show("用户名不存在", "提示", MessageBoxButtons.OK,MessageBoxIcon.Error);
                }else if(result == 2)
                {
                    XtraMessageBox.Show("密码不正确", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else if (result == 3)
                {
                    XtraMessageBox.Show("此账户正在使用", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    XtraMessageBox.Show(string.Format("连接失败，地址[{0}]不可用",user.Url), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            WaitCmdStatus();
        }

        private void MainTab_SelectedPageChanged(object sender, TabPageChangedEventArgs e)
        {
            if (MainTab.SelectedTabPageIndex >= 0)
            {
                XtraTabPage page = MainTab.SelectedTabPage;
                ProjectRootPanel project = (ProjectRootPanel)page.Controls[0];
                ActivateProject = project;
                if (ActivateProject.UserInfo != null)
                {
                    TbCompany.EditValue = ActivateProject.UserInfo.Safety ? ("https://" + ActivateProject.UserInfo.Url) : ("http://" + ActivateProject.UserInfo.Url);
                }
                else
                {
                    TbCompany.EditValue = "wwww.ekootop.com";
                }
                //TbCompany.EditValue = page.t
            }
            else
            {
                ActivateProject = null;
            }
            RefreshToolbar();
        }

        private void TimerProgress_Tick(object sender, EventArgs e)
        {
            Object value = RunningStatus.EditValue;
            if(value is int)
            {
                if ((int)value > 100)
                    RunningStatus.EditValue = 0;
                else
                    RunningStatus.EditValue = (int)value + 10;
            }
            else
            {
                RunningStatus.EditValue = 10;
            }
            
        }
        /// <summary>
        /// 开启进度条 true start false stop
        /// </summary>
        /// <param name="Start"></param>
        public void StartProgress(bool Start)
        {
            RunningStatus.EditValue = 0;
            TimerProgress.Enabled = Start;
        }
        /// <summary>
        /// 附件管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TbAttch_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (attachForm == null) attachForm = new ModuleAttachForm();
            attachForm.RootPanel = ActivateProject;
            attachForm.ShowDialog(this);
        }
        /// <summary>
        /// 单据复制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TbCopyBill_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ActivateProject != null)
            {
                ActivateProject.copyBill();
            }
        }
        /// <summary>
        /// 目录排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TbMenuSort_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if(ActivateProject != null)
            {
                if (menuForm == null) menuForm = new MenuMapingForm(ActivateProject);
                if(menuForm.ShowDialog() == DialogResult.OK)
                {

                }
            }
        }
        /// <summary>
        /// 登录控制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnLogLmt_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if(ActivateProject != null)
            {
                ActivateProject.allowLogin(true);
            }
        }

        private void ButReflect_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if(ActivateProject != null)
            {
                ActivateProject.OpenReflectBill();
            }
        }

        /// <summary>
        /// 保存界面样式
        /// </summary>
        private void saveSkin()
        {
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            configuration.AppSettings.Settings["SetSkinStyle"].Value = UserLookAndFeel.Default.ActiveSkinName;
            configuration.Save();
        }

        private void bBTestItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ExcelReportForm form = new ExcelReportForm(null,null,null);
            form.ShowDialog();
        }
        //下载多语言
        private void TbDownExcel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ActivateProject != null)
            {
                if (SaveLgeDialog.ShowDialog() == DialogResult.OK)
                {
                    string filePath = SaveLgeDialog.FileName;
                    bool success = true;
                    if (File.Exists(filePath))
                    {
                        try
                        {
                            File.Delete(filePath);
                        }
                        catch (Exception ee)
                        {
                            logger.Error("删除文件失败", ee);
                            ActivateProject.ShowAlert("提示", "选择的文件存在且被占用,保存失败");
                            success = false;
                        }
                    }
                    if (success)
                    {
                        ActivateProject.downLanguage(filePath);
                    }
                }

            }
        }
        /// <summary>
        /// 上传多语言
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TbUploadExcel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ActivateProject != null)
            {
                if (OpenLgeDialog.ShowDialog() == DialogResult.OK)
                {
                    string filePath = OpenLgeDialog.FileName;
                    if (File.Exists(filePath))
                    {
                        ActivateProject.upLanguage(filePath);
                    }
                }

            }
        }

        private void TbCopy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if(ActivateProject != null)
            {
                ActivateProject.copyBill();
            }
        }
    }
}
